package com.yc.testupload.util;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * RabbitMQ连接配置类
 */
public class RabbitMQConfig {
    private static final Logger logger = LogManager.getLogger(RabbitMQConfig.class);

    // RabbitMQ服务器地址
    private static final String HOST = "101.42.116.155";
    // RabbitMQ默认端口
    private static final int PORT = 5672;
    // RabbitMQ默认虚拟主机
    private static final String VIRTUAL_HOST = "bthost";
    // RabbitMQ用户名
    private static final String USERNAME = "admin";
    // RabbitMQ密码
    private static final String PASSWORD = "qfLECqwm7XUY7ge4";

    // 微信公众号发布队列名称
    public static final String WECHAT_PUBLISH_QUEUE = "wechat_publish_queue";

    private static ConnectionFactory factory;
    private static Connection connection;
    private static boolean initialized = false;

    static {
        try {
            System.out.println("[RabbitMQConfig] 静态初始化块开始");
            init();
            initialized = true;
            System.out.println("[RabbitMQConfig] 静态初始化块完成");
        } catch (Exception e) {
            logger.error("初始化RabbitMQ连接失败", e);
            System.err.println("[RabbitMQConfig] 初始化RabbitMQ连接失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 初始化RabbitMQ连接
     */
    public static void init() throws IOException, TimeoutException {
        System.out.println("[RabbitMQConfig] 开始初始化连接，连接到: " + HOST + ":" + PORT);

        factory = new ConnectionFactory();
        factory.setHost(HOST);
        factory.setPort(PORT);
        factory.setVirtualHost(VIRTUAL_HOST);
        factory.setUsername(USERNAME);
        factory.setPassword(PASSWORD);

        // 添加连接恢复策略
        factory.setAutomaticRecoveryEnabled(true);
        factory.setNetworkRecoveryInterval(10000);

        try {
            System.out.println("[RabbitMQConfig] 尝试创建连接到RabbitMQ服务器...");
            connection = factory.newConnection();
            logger.info("RabbitMQ连接初始化成功");
            System.out.println("[RabbitMQConfig] RabbitMQ连接初始化成功，连接ID: " + connection.hashCode());
        } catch (Exception e) {
            System.err.println("[RabbitMQConfig] 创建连接失败: " + e.getMessage());
            throw e;
        }
    }

    /**
     * 获取RabbitMQ连接
     */
    public static Connection getConnection() throws IOException, TimeoutException {
        System.out.println("[RabbitMQConfig] 获取连接开始，当前连接状态: " +
                (connection != null ? (connection.isOpen() ? "已连接" : "连接已关闭") : "连接为空"));

        if (connection == null || !connection.isOpen()) {
            System.out.println("[RabbitMQConfig] 连接不存在或已关闭，重新初始化连接...");
            try {
                init();
            } catch (Exception e) {
                System.err.println("[RabbitMQConfig] 重新初始化连接失败: " + e.getMessage());
                throw e;
            }
        }
        return connection;
    }

    /**
     * 关闭连接
     */
    public static void close() {
        try {
            if (connection != null && connection.isOpen()) {
                System.out.println("[RabbitMQConfig] 关闭RabbitMQ连接...");
                connection.close();
                logger.info("RabbitMQ连接已关闭");
                System.out.println("[RabbitMQConfig] RabbitMQ连接已关闭");
            }
        } catch (IOException e) {
            logger.error("关闭RabbitMQ连接失败", e);
            System.err.println("[RabbitMQConfig] 关闭RabbitMQ连接失败: " + e.getMessage());
        }
    }

    /**
     * 检查连接是否可用
     */
    public static boolean isConnectionAvailable() {
        try {
            boolean available = connection != null && connection.isOpen();
            System.out.println("[RabbitMQConfig] 连接可用性检查: " + available);
            return available;
        } catch (Exception e) {
            System.err.println("[RabbitMQConfig] 检查连接可用性时出错: " + e.getMessage());
            return false;
        }
    }
}